import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { useChatMessageStore, useChatStatusStore } from '@/store';
import { aiModelAvatar } from '@/mock-data/mock-chat-view';
import { QUESTIONS } from '@/mock-data/challenge-questions';

type Achievement = {
  id: string;
  name: string;
  description: string;
  earnedAt: number;
};

type Question = {
  id: string;
  level: 'easy' | 'medium' | 'hard';
  category: string;
  title: string;
  content: string;
  choices?: Array<{ key: string; text: string }>;
  answers: string[];
  explanation: string;
  points: number;
};

export const useChallengeStore = defineStore('challenge-store', () => {
  const active = ref(false);
  const questions = ref<Question[]>(QUESTIONS);
  const selectedCategories = ref<string[]>([]);
  const selectedLevels = ref<Array<'easy' | 'medium' | 'hard'>>([]);
  const questionCount = ref<number | undefined>(undefined);
  const currentIndex = ref(0);
  const score = ref(0);
  const streak = ref(0);
  const achievements = ref<Achievement[]>([]);
  const awaitingAnswer = ref(false);
  const persistKey = 'mc-challenge-state';

  const currentQuestion = computed(() => questions.value[currentIndex.value]);

  const reset = () => {
    currentIndex.value = 0;
    score.value = 0;
    streak.value = 0;
    achievements.value = [];
    awaitingAnswer.value = false;
  };

  const start = () => {
    active.value = true;
    reset();
    initQuestions();
    awaitingAnswer.value = true;
    try { useChatStatusStore().startChat = true; } catch {}
    presentQuestionMessage();
    save();
  };

  const stop = () => {
    active.value = false;
    awaitingAnswer.value = false;
    save();
  };

  const next = () => {
    if (currentIndex.value < questions.value.length - 1) {
      currentIndex.value++;
      awaitingAnswer.value = true;
      presentQuestionMessage();
      save();
    } else {
      awaitingAnswer.value = false;
      save();
    }
  };

  const hasAchievement = (id: string) => achievements.value.some(a => a.id === id);

  const grantAchievement = (id: string, name: string, description: string) => {
    if (!hasAchievement(id)) {
      achievements.value.push({ id, name, description, earnedAt: Date.now() });
    }
  };

  const checkAchievements = () => {
    if (score.value >= 50) {
      grantAchievement('score-50', '新锐选手', '累计积分达到 50');
    }
    if (score.value >= 100) {
      grantAchievement('score-100', '实力达人', '累计积分达到 100');
    }
    if (score.value >= 200) {
      grantAchievement('score-200', '闯关之星', '累计积分达到 200');
    }
    if (streak.value >= 3) {
      grantAchievement('streak-3', '三连胜', '连续答对 3 题');
    }
    if (streak.value >= 5) {
      grantAchievement('streak-5', '五连胜', '连续答对 5 题');
    }
  };

  const normalize = (s: string) => s.trim().toLowerCase();

  const isCorrect = (val: string, q: Question) => {
    const v = normalize(val);
    for (const ans of q.answers) {
      if (v === normalize(ans)) return true;
    }
    return false;
  };

  const submitAnswer = (val: string) => {
    if (!active.value || !awaitingAnswer.value) return;
    const q = currentQuestion.value;
    const correct = isCorrect(val, q);
    const chatMessageStore = useChatMessageStore();
    const chatStatusStore = useChatStatusStore();

    chatStatusStore.startChat = true;

    if (correct) {
      score.value += q.points;
      streak.value += 1;
    } else {
      streak.value = 0;
    }

    checkAchievements();

    const summary = correct
      ? `回答正确 ✅ +${q.points}分\n题目：${q.title}\n解析：${q.explanation}\n当前积分：${score.value}`
      : `回答错误 ❌\n题目：${q.title}\n正确答案：${q.answers.join(' / ')}\n解析：${q.explanation}\n当前积分：${score.value}`;

    chatMessageStore.ask(val, summary);

    awaitingAnswer.value = false;
    save();
    next();
  };

  const presentQuestionMessage = () => {
    const chatMessageStore = useChatMessageStore();
    const q = currentQuestion.value;
    const choicesText = q.choices?.length
      ? q.choices.map(c => `${c.key}. ${c.text}`).join('\n')
      : '';
    const content = `第${currentIndex.value + 1}题：${q.title}\n${q.content}${choicesText ? '\n' + choicesText : ''}`;
    chatMessageStore.messages.push({
      from: 'assistant',
      content,
      reasoning_content: '',
      avatarPosition: 'side-left',
      avatarConfig: { ...aiModelAvatar },
      loading: false,
      complete: true,
    });
    chatMessageStore.messageChangeCount++;
  };

  const initQuestions = () => {
    let list = [...QUESTIONS];
    if (selectedCategories.value.length) {
      list = list.filter(q => selectedCategories.value.includes(q.category));
    }
    if (selectedLevels.value.length) {
      list = list.filter(q => selectedLevels.value.includes(q.level));
    }
    if (questionCount.value && questionCount.value > 0) {
      list = list.slice(0, questionCount.value);
    }
    questions.value = list.length ? list : [...QUESTIONS];
    currentIndex.value = 0;
  };

  const setCategories = (arr: string[]) => { selectedCategories.value = arr || []; };
  const setLevels = (arr: Array<'easy' | 'medium' | 'hard'> | string[]) => { selectedLevels.value = (arr as any) || []; };
  const setQuestionCount = (n?: number) => { questionCount.value = n; };

  const save = () => {
    try {
      const raw = JSON.stringify({
        active: active.value,
        currentIndex: currentIndex.value,
        score: score.value,
        streak: streak.value,
        achievements: achievements.value,
        awaitingAnswer: awaitingAnswer.value,
      });
      localStorage.setItem(persistKey, raw);
    } catch {}
  };

  const load = () => {
    try {
      const raw = localStorage.getItem(persistKey);
      if (!raw) return;
      const s = JSON.parse(raw);
      active.value = !!s.active;
      currentIndex.value = Number(s.currentIndex) || 0;
      score.value = Number(s.score) || 0;
      streak.value = Number(s.streak) || 0;
      achievements.value = Array.isArray(s.achievements) ? s.achievements : [];
      awaitingAnswer.value = !!s.awaitingAnswer;
    } catch {}
  };

  load();

  return {
    active,
    questions,
    currentIndex,
    score,
    streak,
    achievements,
    awaitingAnswer,
    currentQuestion,
    start,
    stop,
    next,
    submitAnswer,
    save,
    setCategories,
    setLevels,
    setQuestionCount,
  };
});